package com.skytech.tax.customsdatawarehouse.singlewindow.taxhandle.domain.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.skytech.tax.customsdatawarehouse.common.util.SecurityUtil;
import com.skytech.tax.customsdatawarehouse.singlewindow.taxhandle.domain.dao.GuaranteeLetterDao;
import com.skytech.tax.customsdatawarehouse.singlewindow.taxhandle.domain.dao.GuaranteeMoneyDao;
import com.skytech.tax.customsdatawarehouse.singlewindow.taxhandle.domain.entity.GuaranteeLetter;
import com.skytech.tax.customsdatawarehouse.singlewindow.taxhandle.domain.entity.GuaranteeMoney;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class GuaranteeLetterService {

    private static final Logger LOGGER = LoggerFactory.getLogger(GuaranteeLetterService.class);

    @Value("${customsdatawarehouse.token}")
    private String token;

    @Resource
    private GuaranteeLetterDao guaranteeLetterDao;

    public void save(String guaranteeLetter) {
        if (StringUtils.isEmpty(guaranteeLetter)) return;
        String guaranteeLetterText = SecurityUtil.decrypt3DES(token, guaranteeLetter);
        try {
            JSONObject data = JSON.parseObject(guaranteeLetterText);
            if (data == null) return;
            String socialCreditCode = data.getString("socialCreditCode");
            JSONArray guaranteeLetterArr = data.getJSONArray("guaranteeLetter");
            if (CollectionUtils.isEmpty(guaranteeLetterArr)) return;

            //电子税单列表拆分并存储
            List<GuaranteeLetter> guaranteeLetterList = new ArrayList<>();
            for (int i = 0; i < guaranteeLetterArr.size(); i++) {
                JSONObject item = guaranteeLetterArr.getJSONObject(i);
                guaranteeLetterList.add(new GuaranteeLetter(socialCreditCode, item));
            }
            if (CollectionUtils.isEmpty(guaranteeLetterList)) return;

            guaranteeLetterDao.deleteBy(guaranteeLetterList.stream().map(GuaranteeLetter::getSeqNo).collect(Collectors.toList()));

            guaranteeLetterDao.save(guaranteeLetterList);
        } catch (Exception e) {
            LOGGER.error("保存保函错误", e);
        }
    }
}
